import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, ScrollView, TouchableOpacity, Dimensions, Alert, TextInput } from "react-native";
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common';
import { ProductEditing } from './_components/ProductEditing';
import { API, API_GENERATE } from '../../../config/api';
import { CommonDialog } from '../../../components/common/Dialog';
import ToastUtil from '../../../utils/toast';
import HTTP from '../../../utils/http';
import navigationSeevice from '../../../components/navigation/navigationSeevice';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import { MDMCodeCpt } from './_components/MDMCodeCpt';

const ScreenWidth = Dimensions.get('window').width;
const ScreenHeight = Dimensions.get('window').height;
const scale = ScreenWidth / 375;
const correct = require('../../../imgs/global/correct.png');
const query = require('../../../imgs/global/query.png');
export class projectDetail extends Component {
  static navigationOptions = ({ navigation }) => {
    return {
      title: '客户认领详情',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../imgs/goBackEmpty.png')} />),
      headerStyle: style.head.headerStyle,
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  }

  constructor(props) {
    super(props);
    const { data, choice } = props.navigation.state.params || {};
    const { companyName, lastTransTime, companyId, mdmCode } = data || {};
    this.state = {
      goodsTreeList: [],
      isLock: false,
      modalVisible: false,
      submitVisible: false,
      disableVisible: (data && data.status === 'ABANDONED') ? true : false,
      operationVisible: false,
      intro: '',
      companyName: companyName,
      lastTransTime: lastTransTime,
      searching: true,
      choice,
      mdmCode
    }

    this.params = {
      companyId: companyId || '',
      searchKey: '',
      sourceFlag: 1,
      corpId: choice.corpId
    };
    this.postParams = {
      applyType: "APPLYP",
      comments: '',
      companyId: companyId || '',
      goodsCategoryList: [],
      corpId: choice.corpId
    }
    this.postDate = {}
  }

  async	componentWillMount () {
    console.log('初始化')
    await this.getSorage();
    await this._init();
    console.log('结束')
  }

  //获取业务组织
  async getSorage () {
    const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
    const userInfo = JSON.parse(userInfoJson);
    this.setState({
      userCorpId: userInfo.corpId || ''
    })
  }

  componentWillUnmount () {

  }

  //初始函数
  _init = async () => {
    this.getGoodsData()
  }

  async _getGoodsData (searchCode) {
    this.params.searchKey = searchCode.searchCode;
    let res = await HTTP.POST(API_GENERATE(API.CUSTOMER_DETAIL), this.params);
    this.setState({ goodsTreeList: res, searching: false })
  }

  async getGoodsData () {
    let res = await HTTP.POST(API_GENERATE(API.CUSTOMER_DETAIL), this.params);
    this.setState({ goodsTreeList: res, searching: false })
  }

  checkFrozen () {
    this.setState({
      isLock: !this.state.isLock
    })
  }

  _renderToastWrap = () => {
    return (
      <View style={styles.textRow}>
        <Text style={styles.textRowText}>1. 非企业业务员支持新增产品分类，新增后需走对应审批，审批通过直接关联名下。（仅支持新增业务所在产品组经营范围产品）</Text>
        <Text style={[styles.textRowText]}>2.产品新增审批中，不支持重复新增产品</Text>
      </View>
    )
  }

  _renderSubmitWrap = () => {
    return (
      <View style={styles.textRow}>
        <View style={[styles.flexRow, { marginBottom: 5 * scale }]}>
          <Text style={{ color: 'red', marginRight: 3 * scale }}>*</Text><Text style={{ fontSize: 12 }}>备注</Text>
        </View>
        <TextInput
          style={styles.textInput}
          placeholder={"请输入备注，限定1000字。"}
          underlineColorAndroid={'transparent'}
          placeholderTextColor={"#B4B8C0"}
          maxLength={1000}
          multiline={true}
          returnKeyType='done'
          blurOnSubmit={true}
          onChangeText={(intro) => this.setState({ intro })}
        />
        <TouchableOpacity style={styles.submitButton} onPress={() => this._postmessage()}>
          <Text style={{ fontSize: 14, color: '#fff' }}>提交</Text>
        </TouchableOpacity>
      </View>
    )
  }
  _getGoodsCode = (data) => {
    if (this._isAbandoned()) return;
    this.postParams.goodsCategoryList = []
    this.setState({ submitVisible: true })
    this.postDate = data
    for (var i = 0; i < this.postDate.length; i++) {
      const element = this.postDate[i].goodsList
      for (var j = 0; j < element.length; j++) {
        const data = element[j]
        if (data.select) {
          this.postParams.goodsCategoryList.push(data.goodsCode)
        }
      }
    }
    console.log(this.postParams.goodsCategoryList)
  }

  async _postmessage () {
    if (!this.state.intro) {
      Alert.alert('请填写备注')
      return
    }
    this.postParams.comments = this.state.intro
    let res = await HTTP.POST(API_GENERATE(API.ADD_COMPANY_PRODUCT), this.postParams);
    console.log(res)
    if (res) {
      ToastUtil.showSuccess(`提交成功`).then(() => {
        this.getGoodsData()
      })
    }
    this.setState({ submitVisible: false })
  }

  _renderDisable = () => {
    return (
      <View style={styles.disable}>
        <Image style={styles.icon} source={require('../../../imgs/customer/disable.png')} />
        <Text style={styles.disableText}>您当前访问的企业已废弃，仅查询不支持被认领哦。</Text>
      </View>
    )
  }

  _renderOperation = () => {
    return (
      <View style={styles.disable}>
        <Image style={styles.icon} source={require('../../../imgs/customer/disable.png')} />
        <Text style={styles.disableText}>当前帐套下企业已作废，无法认领</Text>
      </View>
    )
  }

  //是否废弃
  _isAbandoned = () => {
    const { data } = this.props.navigation.state.params || {};
    //废弃  当前帐套下企业已作废，无法认领
    if (data && data.status === 'ABANDONED') {
      this.setState({ operationVisible: true })
      return true;
    }
    return false
  }

  _newCLass = () => {
    if (this._isAbandoned()) return;
    let { choice } = this.state;
    navigationSeevice.navigate('newProject', { companyId: this.params.companyId, choice, pageFrom: 'RL' })
  }

  render () {
    let { goodsTreeList, isLock, modalVisible, submitVisible, companyName, lastTransTime, searching, choice, userCorpId,
      disableVisible, operationVisible, mdmCode } = this.state;
    let { corpId } = choice || {};
    const { data } = this.props.navigation.state.params || {};
    let { isFrozen, status } = data || {};
    return (
      <View style={styles.back}>
        <View style={styles.top}>
          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
            <Text style={[{ color: '#fff', marginRight: 8 * scale }]}>{companyName}</Text>
            {!mdmCode ? <MDMCodeCpt /> : null}
            {isFrozen === "1" ? <Image style={styles.icon} source={require('../../../imgs/customer/suoding.png')} /> : null}
            {status === "ABANDONED" ? <Image style={styles.icon} source={require('../../../imgs/customer/disable.png')} /> : null}
          </View>
          {/* <View><Text style={{ color: '#fff' }}>{choice.corpName}</Text></View> */}
          <View style={[styles.flexRow, { marginTop: 13 * scale, marginBottom: 26 * scale, justifyContent: 'space-between', alignItems: 'center' }]}>
            <Text style={{ color: '#fff', fontSize: 11 }}>上次交易时间：{lastTransTime}</Text>
            <TouchableOpacity style={[styles.flexRow, { alignItems: 'center' }]} onPress={() => this.checkFrozen()}>
              <View style={styles.lockView}>
                {isLock ? <Image style={styles.lockImage} source={correct} /> : null}
              </View>
              <Text style={{ color: '#fff', fontSize: 11 }}>仅看可认领</Text>
            </TouchableOpacity>
          </View>
        </View>
        <ProductEditing
          // confirmPress={this._confirmPress}
          // cancelPress={() => this._cancelPress()}
          searchPress={(searchCode) => {
            this.setState({
              searching: true
            }, () => {
              this._getGoodsData(searchCode)
            })
          }
          }
          data={goodsTreeList || []}
          onlyOption={isLock}
          leftBtnsList={corpId == userCorpId ? {
            btnText: '新增分类',
            btnFun: this._newCLass,
            iconImg: query,
            iconFun: () => { this.setState({ modalVisible: true }) }
          } : null}
          rightBtnsList={corpId == userCorpId ? [{
            btnText: '提交认领',
            btnFun: (data) =>
              this._getGoodsCode(data)
          }] : null}
          secondRight={true}
          optionBox={true}
          searching={searching}
        // bannerBtnContent={'* 已存在的产品可直接发起认领，新增审批中无需重复新增'}
        />
        <CommonDialog modalVisible={modalVisible} title={'提示'} renderCustom={this._renderToastWrap} onClosePress={() => { this.setState({ modalVisible: false }) }} />
        <CommonDialog modalVisible={submitVisible} title={'提示'} renderCustom={this._renderSubmitWrap} onClosePress={() => { this.setState({ submitVisible: false }) }} />
        <CommonDialog confirmBtnTextStylePro={styles.confirmBtnTextStylePro} modalVisible={disableVisible} onConfirmPress={() => { this.setState({ disableVisible: false }) }} confirmBtnText={"知道了"} title={'提示'} renderCustom={this._renderDisable} onClosePress={() => { this.setState({ disableVisible: false }) }} />
        <CommonDialog confirmBtnTextStylePro={styles.confirmBtnTextStylePro} modalVisible={operationVisible} onConfirmPress={() => { this.setState({ operationVisible: false }) }} confirmBtnText={"知道了"} title={'提示'} renderCustom={this._renderOperation} onClosePress={() => { this.setState({ operationVisible: false }) }} />
      </View>
    )
  }
}


const styles = StyleSheet.create({
  flexRow: {
    display: 'flex',
    flexDirection: 'row'
  },
  top: {
    paddingTop: 30 * scale,
    paddingLeft: 22 * scale,
    paddingRight: 22 * scale
  },
  back: {
    flex: 1,
    backgroundColor: "#0087FF"
  },
  lockView: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    height: 12 * scale,
    width: 12 * scale,
    borderWidth: 1 * scale,
    borderColor: '#fff',
    marginLeft: 14 * scale,
    marginRight: 10 * scale,
  },
  lockImage: {
    tintColor: '#fff',
    width: 8 * scale,
    height: 6 * scale
  },
  textRowText: {
    fontSize: 13 * scale,
    lineHeight: 16 * scale,
    marginBottom: 10 * scale
  },
  textRow: {
    paddingLeft: 10 * scale,
    paddingRight: 10 * scale
  },
  textInput: {
    borderWidth: 1 * scale,
    borderColor: '#000',
    borderRadius: 4 * scale,
    padding: 10 * scale,
    height: 122 * scale,
    fontSize: 12 * scale,
  },
  submitButton: {
    marginTop: 80 * scale,
    height: 35 * scale,
    width: 100 * scale,
    backgroundColor: '#0E7FFD',
    borderRadius: 15 * scale,
    alignSelf: 'center',
    justifyContent: 'center',
    alignItems: 'center',
    // fontFamily: 'PingFangSC-Semibold'
  },
  disable: {
    flexDirection: 'row',
    paddingHorizontal: 25 * scale
  },
  disableText: {
    fontSize: 14 * scale,
    color: '#B01703',
    lineHeight: 20 * scale
  },
  icon: {
    height: 15 * scale,
    width: 15 * scale,
    marginRight: 5 * scale,
    marginTop: 3 * scale
  },
  confirmBtnTextStylePro: {
    marginBottom: 20 * scale
  },
  icon: {
    height: 13 * scale,
    width: 13 * scale,
    marginRight: 5 * scale
  }
})